﻿using System;
using System.Collections;
using Library;
using Library.Util;

namespace Cloud
{
    public partial class ErrorPage : System.Web.UI.Page
    {
        private ArrayList _exceptions;
        private string _stackTrace;
        private int _exceptionCount;

        protected void Page_Load(object sender, EventArgs e)
        {
            var exceptionId = Request.QueryString["ExceptionId"];
            if (String.IsNullOrEmpty(exceptionId)) return;
            _exceptionCount = 0;
            _exceptions = new ArrayList();
            _stackTrace = "";
            ParseExceptions(Session[exceptionId] as Exception);
            for (var i = 0; i < _exceptions.Count; i++)
                _frmHataMesaji.Text += (i + 1) + ". " + _exceptions[i] + "<br />";
            _frmStackTrace.Text = _stackTrace.Replace("konum: ", "").Replace("at ", "");
        }

        private void ParseExceptions(Exception ex)
        {
            if (ex == null)
                return;

            if (ex.GetType().Name == "TargetInvocationException" && ex.InnerException != null)
                ParseExceptions(ex.InnerException);
            else
            {
                _exceptionCount++;

                if (ex.GetType() == typeof(NetException))
                {
                    var exN = (NetException)ex;
                    _exceptions.Add(AppMessage.Get(exN.MessageText, exN.MessageParts));
                }
                else
                {
                    _exceptions.Add(AppMessage.Get(ex.Message));
                }

                if (ex.StackTrace != null && ex.StackTrace.Contains("\n"))
                {
                    string[] stackTrace = ex.StackTrace.Split('\n');
                    for (int i = 0; i < stackTrace.Length; i++)
                    {
                        stackTrace[i] = stackTrace[i].Replace("\r", "");
                        if (stackTrace[i].Trim().StartsWith("at NHibernate") || stackTrace[i].Trim().StartsWith("konum: NHibernate"))
                            continue;
                        if (stackTrace[i].Substring(stackTrace[i].Length - 2) == stackTrace[i].Substring(stackTrace[i].Length - 2).ToUpper())
                            _stackTrace += stackTrace[i].Trim() + "<br />";
                    }
                }
                if (ex.InnerException != null)
                    ParseExceptions(ex.InnerException);
            }
        }
    }
}